import * as XLSX from 'xlsx';

export const downloadXlsx = (dataList, fileName) => {
    try {
        // 创建表格
        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.aoa_to_sheet(dataList);
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

        // 将工作簿写入为二进制数据
        const xlsxBinary = XLSX.write(workbook, {
            bookType: 'xlsx',
            type: 'array', // 直接生成 Uint8Array，避免手动转换
        });

        // 创建 Blob 对象
        const xlsxBlob = new Blob([xlsxBinary], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });

        // 创建下载链接
        const a = document.createElement('a');
        a.href = URL.createObjectURL(xlsxBlob);
        a.download = fileName || 'download.xlsx'; // 默认文件名
        a.click();

        // 释放 Blob URL
        URL.revokeObjectURL(a.href);
    } catch (error) {
        console.error('导出 Excel 文件失败:', error);
        alert('导出 Excel 文件失败，请稍后重试。');
    }
};